﻿using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.Adapters;
using System.Web.UI.WebControls;
using umbraco.BusinessLogic;

namespace TheOutfield.UmbExt.PageNotifications
{
    public class IndicatorAdapter : PageAdapter
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var environment = Environment.Instance.ConfiguredEnvironment;

            var userTypeAlias = new User(umbraco.helper.GetCurrentUmbracoUser().Id).UserType.Alias;
            foreach (var notification in Config.Instance.Notifications)
            {
                var notif = notification;
                
                if (notif.Type == NotificationType.Environment && notif.IndicatorBar.UserTypeAliases.Contains(userTypeAlias) == false)
                    return;
            }

            var color = "";
            foreach (var notification in Config.Instance.Notifications)
            {
                var notif = notification;

                if (notif.Type == NotificationType.Environment == false)
                    continue;
                
                foreach (var bar in notif.IndicatorBar.Bars.Where(bar => bar.Key == environment))
                    color = bar.Value;
            }

            if (color == "")
                return;

            var notificationBarText = string.Format(
                "<div style=\"height: 3px; widht: 100%; background-color: {0};\"><span style=\"font-size: 1px; line-height: 1px;\">&nbsp;</span></div>"
                , color);
            AddHtmlToPage(notificationBarText);

            var saveButtonConfirmations = "<script type=\"text/javascript\">$(function () { $('input[type=image]').each(function () { var altText = $(this).attr('alt'); alert(altText); }); });</script>";
            AddHtmlToPage(saveButtonConfirmations);
        }

        private void AddHtmlToPage(string html)
        {
            var scriptManager = (ScriptManager)Page.FindControl("umbracoScriptManager");
            var notificationBar = new Literal { Text = html };
            scriptManager.Controls.Add(notificationBar);
        }
    }
}